//
//  UploadPictureController.swift
//  Fancyswap
//
//  Created by Jonathan Muschalle on 2015-03-15.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//

import UIKit
import Foundation

class UploadPictureController: UICollectionViewController {

    let UPLOAD_STATUS_SUCCESS:Int = 1
    let UPLOAD_PICTURE_ICON_FONT_SIZE:CGFloat = 20
    let PROGRESS_NEXT_UPDATE_GAP:Float = 0.1
    
    @IBOutlet var collection: UICollectionView!
    @IBOutlet weak var nextButton: UIBarButtonItem!
    @IBOutlet var col: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if(pictureListToAdd.isAllPicturesUploaded()) {
            self.performSegueWithIdentifier("detailForm", sender: nil)
        }
    }
    override func viewDidAppear(animated: Bool) {
        uploadPictures()
        self.collectionView?.reloadData()
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureListToAdd.getTotalPictures()
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UploadPictureCell", forIndexPath: indexPath) as UploadPictureCell
        
        let currentPic = pictureListToAdd.getPictureById(indexPath.row)
        renderUploadPictureCell(cell, picture: currentPic)
        
        return cell
    }
    
    func renderUploadPictureCell(cell: UploadPictureCell, picture: PictureToAdd) {
        cell.picture.image = picture.getImageObject()
        cell.progress.setProgress(picture.getUploadProgress(), animated: false)
        
        cell.icon.font = UIFont.fontAwesomeOfSize(UPLOAD_PICTURE_ICON_FONT_SIZE)
        if(picture.isPictureUploaded()) {
            cell.descriptionText.text = "Téléchargé!"
            cell.icon.text = String.fontAwesomeIconWithName(FontAwesome.CheckCircle)
        } else {
            cell.icon.text = String.fontAwesomeIconWithName(FontAwesome.Download)
        }
        

    }
    
    func uploadPictures() {
        let uploadRequestUrl = "http://api.fancyswap.com/rest/1.0/upload/\(pictureListToAdd.getUploadFormId())"
        for picToAdd in pictureListToAdd.getPictureListToUpload() {
            uploadPictureToServer(picToAdd, uploadRequestUrl: uploadRequestUrl, progressEvent: onUploadingPicture, responseEvent: didUploadPicture)
        }
        
        
    }
    
    func uploadPictureToServer(currentPicToAdd: PictureToAdd, uploadRequestUrl: String,progressEvent: (Int64, Int64, Int, UploadPictureController) -> (), responseEvent: (AnyObject, Int) -> ()) {
        
        let image = currentPicToAdd.getImageObject()
        let imageData = UIImagePNGRepresentation(image)
        let urlRequest = getUrlRequestWithImageComponents(uploadRequestUrl, imageData: imageData, imageName: currentPicToAdd.getUniqueName())
        
        let pictureIndex = pictureListToAdd.searchPictureIndexByUniqueName(currentPicToAdd.getUniqueName())
        
        var currentController = self
        
        upload(urlRequest.0, urlRequest.1)
            .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
                progressEvent(totalBytesWritten, totalBytesExpectedToWrite, pictureIndex, currentController)
            }
            .responseJSON { (request, response, JSON, error) in
                responseEvent(JSON!, pictureIndex)
        }
    }
    
    // this function creates the required URLRequestConvertible and NSData we need to use Alamofire.upload
    func getUrlRequestWithImageComponents(urlString:String, imageData:NSData, imageName:String) -> (URLRequestConvertible, NSData) {
        
        // create url request to send
        var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        mutableURLRequest.HTTPMethod = Method.POST.rawValue
        let boundaryConstant = "myRandomBoundary12345"
        let contentType = "multipart/form-data;boundary="+boundaryConstant
        mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
        
        // create upload data to send
        let uploadData = NSMutableData()
        
        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"\(imageName).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData)
        uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        
        return (ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
    }
  
    
    func onUploadingPicture(totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64, index: Int, controller: UploadPictureController) {
        
        let totalBytesWrittenNumber = NSNumber(longLong: totalBytesWritten)
        let totalBytesExpectedToWriteNumber = NSNumber(longLong: totalBytesExpectedToWrite)
        
        let progressUpload = totalBytesWrittenNumber.floatValue / totalBytesExpectedToWriteNumber.floatValue
        
        let lastProgress = pictureListToAdd.getPictureUploadProgressByIndex(index)
        let diffProgress = progressUpload - lastProgress
        pictureListToAdd.updatePictureUploadProgressByIndex(index, progress: progressUpload)
        dispatch_async(dispatch_get_main_queue(),{
            self.reloadCollection()
        })
    }
    
    func reloadCollection() {
        self.collectionView?.reloadData()
    }
    
    func didUploadPicture(jsonResult: AnyObject, index: Int) {
        if let status = jsonResult["status"] as? Int {
            if status == UPLOAD_STATUS_SUCCESS {
                if let file = jsonResult["file"] as? NSDictionary {
                    if let fileName = file["fileName"] as? String {
                        if(status == UPLOAD_STATUS_SUCCESS) {
                            pictureListToAdd.setUploadedPicture(fileName)
                            self.collectionView?.reloadData()
                            if(pictureListToAdd.isAllPicturesUploaded()) {
                                self.performSegueWithIdentifier("detailForm", sender: nil)
                            }
                            
                        } else {
                            let status = jsonResult["message"] as? Int
                            UploadPictureException(name: "errorDuringUpload", reason: "error during picture upload : \(jsonResult)").raise()
                        }
                    } else {
                        UploadPictureException(name: "wrongUploadResponseFormat", reason: "No file information into the response : \(jsonResult)").raise()
                    }
                }
            } else {
                let status = jsonResult["message"] as? Int
                UploadPictureException(name: "errorDuringUpload", reason: "error during picture upload : \(jsonResult)").raise()
            }
        } else {
            UploadPictureException(name: "wrongUploadResponseFormat", reason: "Response from upload is invalid : \(jsonResult)").raise()
        }
    } 

}
